<template>
    <view class="padding">
        <wd-swiper height=150 class="swiper-border" value-key="url" :list="customSwiperList" autoplay></wd-swiper>
    </view>
	<view class="message-box padding margin border" @click="this.naviTo('/pages/notice/index')">
	    <span class="iconfont icon-small">&#xe626;</span>
	    <span class="message-text">消息盒子</span>
	    <span class="separator"></span>
	    <span class="content-wrapper">
			<span v-if="this.announceList.length > 0" class="content">{{this.announceList[0].content}}</span>
		</span>
	    <span class="arrow">›</span>
	</view>
    <view class="margin" style="margin-top: 10px;border-radius: 10px;">
        <wd-grid :column="3" bg-color="var(--white-color)" style="height: 80px;border-radius: 10px;">
            <wd-grid-item v-for="(item, index) in gridItems" :key="index"
                          @click="item.clickAction && item.clickAction()" use-text-slot use-icon-slot>
				<template #text>
					<view class="text">{{item.text}}</view>
				</template>
                <template #icon>
                    <view class="iconfont icon-large blue" v-html="item.icon"></view>
                </template>
            </wd-grid-item>
        </wd-grid>
    </view>
    <view class="border margin" style="border-radius: 10px;">
        <wd-grid style="padding: 2px;" :column="3" bg-color="var(--bg-color)">
            <wd-grid-item v-for="(item, index) in functionGridItems" :key="index"
                          @click="item.clickAction && item.clickAction()" use-text-slot use-icon-slot>
				<template #text>
					<view class="text">{{item.text}}</view>
				</template>
                <template #icon>
                    <view :style="{ color: item.color ?? '' }"  class="iconfont icon-large gray" v-html="item.icon"></view>
                </template>
            </wd-grid-item>
        </wd-grid>
    </view>
    <view>
        <OverviewCard>
            <template #title>
                <span>设备概览</span>
            </template>
            <template #more>
                <div @click="switchTab('/pages/equipment/index',1)" class="blue">更多</div>
            </template>
            <template #content>
                <div>
                    <div>{{equipmentTotal.allTotal}}</div>
                    <div>总计</div>
                </div>
                <div>
                    <div style="color: green;">{{equipmentTotal.onlineTotal}}</div>
                    <div>在线</div>
                </div>
                <div>
                    <div style="color: coral;">{{equipmentTotal.unlineTotal}}</div>
                    <div>离线</div>
                </div>
            </template>
        </OverviewCard>
    </view>
    <view>
        <OverviewCard>
            <template #title>
                <span>报警概览</span>
            </template>
            <template #more>
                <div @click="switchTab('/pages/warn/index',1)" class="blue">更多</div>
            </template>
            <template #content>
                <div>
                    <div style="color: brown;">{{alarmTotal.total}}</div>
                    <div>今日报警</div>
                </div>
                <div>
                    <div style="color: green;">{{alarmTotal.processed}}</div>
                    <div>今日处理</div>
                </div>
                <div>
                    <div style="color: green;">{{alarmTotal.score}}</div>
                    <div>处理率</div>
                </div>
            </template>
        </OverviewCard>
    </view>
	<AlertCard
      :visible="isCardVisible"
      content="存在未读消息,请注意查看"
      @close="isCardVisible = false"
	  @confirm="this.handleModalAction('notice')"/>
</template>

<script>
    import OverviewCard from '@/common/component/OverviewCard.vue'
    import request from '@/util/request';
	import AlertCard from "@/common/component/AlertCard.vue"
    export default {
        components: {
            OverviewCard,AlertCard
        },
		created() {
			setTimeout(()=>{
				this.init()
			},1000)
		},
        onLoad() {
            this.hasAnnounce()
        },
		onShow() {
			this.getAnnounce()
			this.getEquipmentTotal()
			this.getAlarmTotal()
		},
        data() {
            return {
				isCardVisible: false,
				modalButtons: [
					{ label: '确定', action: 'confirm' },
					{ label: '取消', action: 'cancel' }
				],
                equipmentTotal: {
                    allTotal: '',
                    onlineTotal: '',
                    unlineTotal: ''
                },
                alarmTotal: {
                    total: '',
                    processed: '',
                    score: ''
                },
                announceList: [
                    {content: ''}
                ],
                customSwiperList: [{
                    url: '../../static/home/top1.png',
                    title: '消防安全！'
                },
                    {
                        url: '../../static/home/top2.jpg',
                        title: '消防安全！'
                    },
                    {
                        url: '../../static/home/top3.png',
                        title: '消防安全！'
                    },
                    {
                        url: '../../static/home/top4.jpg',
                        title: '消防安全！'
                    }
                ],
                gridItems: [{
                    icon: "&#xe60b;",
                    text: "设备管理",
                    clickAction: () => this.switchTab('/pages/equipment/index',0)
                },
                    {
                        icon: "&#xe67a;",
                        text: "报警管理",
                        clickAction: () => this.switchTab('/pages/warn/index',0)
                    },
                    {
                        icon: "&#xe604;",
                        text: "单位管理",
                        clickAction: () => this.naviTo('/pages/client/index')
                    }
                ],
                functionGridItems: [{
                    icon: "&#xe602;",
                    text: "账号信息",
					color: "#FF5733", // 橙色
                    clickAction: () => this.naviTo('/pages/my/account')
                },
                    {
                        icon: "&#xe635;",
                        text: "统计报表",
						 color: "#33B5FF", // 蓝色
                        clickAction: () => this.naviTo('/pages/report/index')
                    },
                    {
                        icon: "&#xe73a;",
                        text: "通知管理",
						color: "#4CAF50", // 绿色
                        clickAction: () => this.naviTo('/pages/notice/index')
                    },
                    {
                        icon: "&#xe606;",
                        text: "巡检管理",
						color: "#FFC107", // 橙色
                        clickAction: () => this.naviTo('/pages/inspection/index')
                    },
                    {
                        icon: "&#xe651;",
                        text: "维保管理",
						color: "#9C27B0", // 橙色
                        clickAction: () => this.naviTo('/pages/maintenance/index')
                    },
                    {
                        icon: "&#xe608;",
                        text: "查岗管理",
						color: "#FF5722", // 橙色
                        clickAction: () => this.naviTo('/pages/check/index')
                    }
                ]
            }
        },
        methods: {
			// 未读通知弹窗
			hasAnnounce(){
				request.get("/announce/hasAnnounce?userId="+this.$store.state.userInfo.id).then(res=>{
					this.isCardVisible=res.data
				})
			},
			handleModalAction(action) {
			  if (action === 'notice') {
				this.naviTo("/pages/notice/index")
			  }
			  this.isModalVisible = false;
			},
            switchTab(url,tab) {
                if (url !== undefined) {
                    uni.switchTab({
                        url: url,
                    });
                }
            },
            naviTo(url) {
                if (url !== undefined) {
                    uni.navigateTo({
                        url: url
                    })
                }
            },
            getEquipmentTotal() {
                let level = this.$store.state.userInfo.level;
                let organizationId = this.$store.state.userInfo.organization;
                let isAllClient = this.$store.state.userInfo.isAllClient;
                let clientIds;
                if (isAllClient === "1") {
                    clientIds = this.$store.state.userInfo.clientIds;
                } else {
                    clientIds = [];
                }
                request.get("/equipment-input-store/findCountByOnline?level=" + level + "&organizationId=" + organizationId + "&isAllClient=" + isAllClient + "&clientIds=" + clientIds).then(res => {
                    if (res.code === '200') {
                        this.equipmentTotal = res.data;
                    }
                })
            },
            getAlarmTotal() {
                let level = this.$store.state.userInfo.level;
                let organizationId = this.$store.state.userInfo.organization;
                let isAllClient = this.$store.state.userInfo.isAllClient;
                let clientIds;
                if (isAllClient === "1") {
                    clientIds = this.$store.state.userInfo.clientIds;
                } else {
                    clientIds = [];
                }
                request.get("/warn-record/findTodayProcessScore?level=" + level + "&organizationId=" + organizationId + "&isAllClient=" + isAllClient + "&clientIds=" + clientIds).then(res => {
                    if (res.code === '200') {
                        this.alarmTotal = res.data;
                    }
                })
            },
            getAnnounce() {
                let userId = this.$store.state.userInfo.id;
                let level = this.$store.state.userInfo.level;
                let organizationId = this.$store.state.userInfo.organization;
                let isAllClient = this.$store.state.userInfo.isAllClient;
                let clientIds;
                if (isAllClient === "1") {
                    clientIds = this.$store.state.userInfo.clientIds;
                } else {
                    clientIds = [];
                }
                request.get("/announce/findByUserId?pageNum="+1+"&pageSize="+1+"&level="+level+"&organizationId="+organizationId+"&isAllClient="+isAllClient+"&clientIds="+clientIds+"&userId="+userId).then(res => {
                    if(res.code==='200') {
                        console.log(res.data.record)
                        this.announceList = res.data.record
                    }
                })
            },
			// 初始化
			init() {
				this.checkVersion()
			},
			//检查版本更新情况
			checkVersion() {
                const version = plus.runtime.version
                request.get("/version/getVersion", {
                    params: {
                        version: version,
                    }
                }).then(versionRes => {
                    if (versionRes.code === "200") {
                        if (versionRes.data.isUpdate) {
                            uni.showModal({
                                title: '更新提示',
                                content: '发现新版本，是否立即更新？',
                                success: (res) => {
                                    if (res.confirm) {
                                        this.downloadUpdate(versionRes.data.url);
                                    }
                                }
                            });
                        }
                    }
                })
			},
            downloadUpdate(downloadUrl) {
                // 显示下载进度
                const downloadTask = uni.downloadFile({
                    url: downloadUrl,
                    success: (downloadResult) => {
                        if (downloadResult.statusCode === 200) {
                            plus.runtime.install(downloadResult.tempFilePath, {
                                force: false
                            }, function () {
                                uni.showToast({
                                    title: '安装完成',
                                    icon: 'success'
                                });
                            }, function (e) {
                                uni.showToast({
                                    title: '安装失败',
                                    icon: 'error'
                                });
                            });
                        }
                    }
                });

                // 监听下载进度
                downloadTask.onProgressUpdate((res) => {
                    console.log('下载进度：' + res.progress + '%');
                    // 可以在这里更新UI显示进度
                });
            }
        }
    }
</script>

<style scoped>
    :deep(.customTextClass) {
        position: absolute;
        top: 24 rpx;
        right: 24 rpx;
        color: #ffffff;
        font-size: 24 rpx;
        text-shadow: 0 0 8 rpx #000000;
    }

    .icon-grid {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
    }

    .icon-item {
        text-align: center;
        width: 80px;
    }

    .device-summary {
        margin-top: 20px;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .summary-item {
        text-align: center;
    }

    .message-box {
        border-radius: 10px;
        height: 30px;
        display: flex;
        align-items: center;
        overflow: hidden;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

    .border {
        border: 1px solid #e0e0e0;
        /* 边框颜色 */
    }

    .swiper-border {
        /* 边框颜色 */
        border-radius: 10px;
        /* 圆角 */
        box-shadow: 0 2px 4px rgba(62, 62, 62, 0.5);
    }

    .separator {
        border-right: 1px solid var(--gray-color);
        /* 竖线颜色 */
        height: 20px;
        margin: 0 10px;
    }

    .content-wrapper {
        flex-grow: 1;
        overflow: hidden;
        /* 隐藏滚动内容的溢出 */
        position: relative;
        width: 60%;
        /* 设置宽度限制滚动区域 */
        margin-right: 8px;
        /* 保持与箭头的间距 */
    }

    .content {
        /* 内容颜色 */
        flex: 1;
        display: inline-block;
        white-space: nowrap;
        animation: scroll 10s linear infinite;
    }

    @keyframes scroll {
        0% {
            transform: translateX(30%);
        }

        100% {
            transform: translateX(-40%);
        }
    }

    .arrow {
        /* 箭头颜色 */
        color: var(--gray-color);
        margin-left: 10px;
    }
	.message-text{
		min-width: 75x;
	}
    .content,
    .title {
        display: flex;
        flex-direction: row;
        justify-content: flex-start;
        align-items: center;
    }

    .content {
        justify-content: flex-start;
    }

    .title {
        justify-content: space-between;
    }
	.text{
		margin-top: 10px;
		font-size: 15px;
	}
</style>
